package com.hongdee.scm.buyModel.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.buyModel.dao.ITScmBuyModelDao;
import com.hongdee.scm.buyModel.entity.TScmBuyModel;
import com.hongdee.scm.buyModel.service.ITScmBuyModelService;
import com.hongdee.scm.common.service.impl.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 名  称:TScmBuyModelServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.buyModel.service.impl
 * 作  者: 术洪超
 * 日  期:2017-04-27 22:14
 */
@Service
public class TScmBuyModelServiceImpl implements ITScmBuyModelService {

    String tabName = "T_SCM_BUYMODEL";

    @Autowired
    private ITScmBuyModelDao itScmBuyModelDao;

    /**
     * @param data 要保存的采购单车型实体
     * @return Map
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @Override
    public TScmBuyModel saveOrUpdate(TScmBuyModel data, String uid) throws Exception {

        //id为空时则为添加
        if (data.getId() == null) {
            if (data.getOrderCodeId() != null) {
                if (existCode(data.getOrderCodeId())) {
                    throw new Exception("该采购单已经存在！");
                }
            }
            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());

        } else {
            //id不为空时则为修改
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());

        }
        data.setCompanyId(TokenUtil.getCompanyId(uid));
        this.itScmBuyModelDao.saveOrUpdate(data);
        return data;

    }

    /**
     * @param uid 登录用户 ID
     * @param id  主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */

    @Override
    public Map info(String id, String uid) throws Exception {

        List params = new ArrayList();
        String sql = "select * from " + tabName + " b where id = ? and b.company_id= ?";
        params.add(id);
        params.add(TokenUtil.getCompanyId(uid));

        return this.itScmBuyModelDao.info(sql, params.toArray());
    }

    /*
    判断采购单ID是否存在，用于保存时判断采购单是否重复
     */
    private boolean existCode(String orderCodeId) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName + " b ");

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!orderCodeId.isEmpty() && !orderCodeId.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" b.order_code_id = ? ");
            params.add(orderCodeId);
        }

        Map map = this.itScmBuyModelDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }


}
